﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace BaseData.ReadAPI.Controllers
{
    /// <summary>
    /// 上传图片有参数
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    [ApiExplorerSettings(GroupName = "UpFile")]
    public class UpFileController : ControllerBase
    {
        private readonly IConfiguration configuration;
        private readonly IWebHostEnvironment webHostEnvironment;

        public UpFileController(IConfiguration configuration,IWebHostEnvironment webHostEnvironment)
        {
            this.configuration = configuration;
            this.webHostEnvironment = webHostEnvironment;
        }

        /// <summary>
        /// 上传图片有参数
        /// </summary>
        /// <param name="formFile"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost]
        public async Task<IActionResult> UpImg(IFormFile formFile)
        {
            //判断大小
            var size = formFile.Length/1024;
            if (size > Convert.ToInt64(configuration["UpLoadConfig:Limit"]))
            {
                throw new Exception("文件大小不能大于2000");
            }
            //判断格式
            var ext = Path.GetExtension(formFile.FileName);
            if (!configuration["UpLoadConfig:ExtName"].Split(',').Any(x=>x == ext.Trim('.')))
            {
                throw new Exception("文件格式不正确");
            }
            //创建目录
            Directory.CreateDirectory($"{webHostEnvironment.WebRootPath}/Uploadfiles/Img/{DateTime.Now.ToString("yyyyMMdd")}/");
            //重命名文件名称
            var f = $"{DateTime.Now.ToString("yyyyMMddHHmmss")}-{Random.Shared.Next(1000,9999)}{ext}";
            var path = $"{webHostEnvironment.WebRootPath}/Uploadfiles/Img/{DateTime.Now.ToString("yyyyMMdd")}/{f}";
            //创建文件流
            using (FileStream fs = System.IO.File.Create(path))
            {
                formFile.CopyTo(fs);
                fs.Close();
            }
            return Ok($"/Uploadfiles/Img/{DateTime.Now.ToString("yyyyMMdd")}/{f}");
        }
    }
}
